package fina2.dcs.fis;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;

import fina2.dcs.i18n.LanguageSession;
import fina2.dcs.system.SysString;
import fina2.dcs.system.SysStringLocal;
import fina2.dcs.system.SysStringPk;

@Stateful
@Name("licTypeSession")
@Scope(ScopeType.SESSION)
@LocalBinding(jndiBinding = "LicenceTypeSession/local")
@AutoCreate
public class LicenceTypeSession implements LicenceTypeLocal,Serializable {

	@PersistenceContext
	private EntityManager em;
	
	@Logger
	private Log log;
	
	@DataModel
	private List<LicenceType> licences = new ArrayList<LicenceType>();

	private LicenceType licType = new LicenceType();

	private LicenceType selectedLicType = new LicenceType();

	private boolean success = false;

	
	@EJB
	private SysStringLocal sysStringLocal;

	private final BigDecimal defaultIndex = new BigDecimal("1");

	@Remove
	@Destroy
	public void remove() {

	}

	@SuppressWarnings("unchecked")
	@Factory("licenceDescriptions")
	public void init() {
		try {
			log.info("Initializing licence types...");

			

			licences = em.createQuery("FROM " + LicenceType.class.getName() + " l").getResultList();

			List<BigDecimal> licenceNameStrIds = new ArrayList<BigDecimal>();
			for (int i = 0; i < licences.size(); i++)
				licenceNameStrIds.add(licences.get(i).getNamestrid());
			StringBuffer sb = new StringBuffer(licenceNameStrIds.toString());

			sb.replace(0, 1, "");
			sb.replace(sb.toString().length() - 1, sb.toString().length(), "");

			List<SysString> licenceDescriptions = sysStringLocal.getAllValues(sb.toString(), LanguageSession.langId);

			for (int i = 0; i < licences.size(); i++) {
				for (int j = 0; j < licenceDescriptions.size(); j++) {
					if (licences.get(i).getNamestrid().toString().trim().equals(licenceDescriptions.get(j).getPk().getId().toString().trim())) {
						licences.get(i).setDescription(licenceDescriptions.get(j).getValue());
						break;
					}
				}
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public String addLicenceType() {
		try {
			LicenceType lt = new LicenceType();
			lt.setId(getMaxId().add(defaultIndex));
			lt.setNamestrid(sysStringLocal.getMaxId().add(defaultIndex));
			em.persist(lt);

			SysString ss = new SysString();
			SysStringPk sspk = new SysStringPk();
			sspk.setId(lt.getNamestrid());
			sspk.setLangId(LanguageSession.langId);
			ss.setPk(sspk);
			ss.setValue(licType.getDescription());
			sysStringLocal.addString(ss);

		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			licType = new LicenceType();
		}
		return "licenceTypeAdded";
	}

	public void removeLicenceType() {
		try {
			BigDecimal id = selectedLicType.getNamestrid();
			LicenceType lt = em.find(LicenceType.class, selectedLicType.getId());
			em.remove(lt);
			SysStringPk pk = new SysStringPk(id, LanguageSession.langId);
			sysStringLocal.removeString(pk);
			success = true;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {
			selectedLicType = new LicenceType();
		}

	}

	public String updateLicenceType() {
		try {
			BigDecimal id = selectedLicType.getNamestrid();
			SysStringPk pk = new SysStringPk(id, LanguageSession.langId);
			SysString ss = sysStringLocal.findByPk(pk);
			ss.setValue(selectedLicType.getDescription());
			sysStringLocal.updateString(ss);
			success = true;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		} finally {

		}

		return "licenceTypeUpdated";
	}

	public BigDecimal getMaxId() {
		BigDecimal maxId = new BigDecimal("0");
		try {
			maxId = (BigDecimal) em.createQuery("SELECT MAX(id) FROM " + LicenceType.class.getName() + " l").getSingleResult();
			if (maxId == null)
				maxId = defaultIndex;
		} catch (NoResultException ex) {
			maxId = defaultIndex;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return maxId;
	}

	public LicenceType findByNameStrid(BigDecimal nameStrId) {
		LicenceType lt = null;
		try {
			lt = (LicenceType) em.createQuery("FROM " + LicenceType.class.getName() + " l WHERE l.namestrid=?").setParameter(1, nameStrId).getSingleResult();
		} catch (NoResultException ex) {
			return lt;
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return lt;
	}

	public LicenceType getLicType() {
		return licType;
	}

	public void setLicType(LicenceType licType) {
		this.licType = licType;
	}

	public LicenceType getSelectedLicType() {
		return selectedLicType;
	}

	public void setSelectedLicType(LicenceType selectedLicType) {
		this.selectedLicType = selectedLicType;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public LicenceType findById(BigDecimal id) {
		LicenceType lc = null;
		try {
			lc = em.find(LicenceType.class, id);
			if (lc != null)
				lc.setDescription(sysStringLocal.findByPk(new SysStringPk(lc.getNamestrid(), LanguageSession.langId)).getValue());
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
		return lc;
	}

	public List<LicenceType> getLicences() {
		return licences;
	}

	public void setLicences(List<LicenceType> licences) {
		this.licences = licences;
	}
    
	
}
